//
//  DetailsViewController.m
//  ABColoringBook
//
//  Created by Oli Chira on 11/6/12.
//  Copyright (c) 2012 Oli Chira. All rights reserved.
//

#import "DetailsViewController.h"

@interface DetailsViewController ()

@end

@implementation DetailsViewController

@synthesize dataObject, mainImg, activeDrawImg, backImg, frontImg, lblStatus;
@synthesize myPopover;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self defaultValues];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)defaultValues{
    
    if (opacity == 0.0) {
        red = 0.0/255.0;
        green = 0.0/25.0;
        blue = 0.0/155.0;
        brush = 8.0;
        opacity = 1.0;
    }
    
    lblStatus.text = @"Start Drawing by tapping the button";
    colorez = NO;

    // daca exista deja poza colorata sa se incarce aia, daca nu, cea standard. TREBUIE facut un model.
    mainImg.image = [UIImage imageNamed:dataObject];
    
    // frontImg trebuie sa fie cu transparenta, doar conturul
    frontImg.image = [UIImage imageNamed:dataObject];
    
    // backImg.image = [UIImage imageNamed:dataObject];
}

//- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer {
//    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
//    recognizer.scale = 1;
//}
//
//- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
//    
//    CGPoint translation = [recognizer translationInView:self.view];
//    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
//                                         recognizer.view.center.y + translation.y);
//    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
//    
//}

- (IBAction)runStartDrawing:(UIButton *)sender {
    colorez = YES;
    lblStatus.text = @"Save your drawing to the photo album";
}

- (IBAction)runSaveImg:(id)sender {
    colorez = NO;
    lblStatus.text = @"Drawing has been saved to your photo album.";
    
    UIGraphicsBeginImageContext(self.mainImg.frame.size);
    
    [self.mainImg.image drawInRect:CGRectMake(0, 0, self.mainImg.frame.size.width, self.mainImg.frame.size.height) blendMode:kCGBlendModeNormal alpha:1.0];
    [self.frontImg.image drawInRect:CGRectMake(0, 0, self.mainImg.frame.size.width, self.mainImg.frame.size.height) blendMode:kCGBlendModeNormal alpha:opacity];
    
    self.mainImg.image = UIGraphicsGetImageFromCurrentImageContext();
    //self.activeDrawImg.image = nil;
    UIGraphicsEndImageContext();
    
    
    UIGraphicsBeginImageContextWithOptions(self.mainImg.bounds.size, NO, 0.0);
    [self.mainImg.image drawInRect:CGRectMake(0, 0, self.mainImg.frame.size.width, self.mainImg.frame.size.height)];
    UIImage *SaveImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(SaveImage, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
    
//    if ([UIDevice currentDevice] )
}

- (IBAction)runReset:(id)sender {
    mainImg.image = [UIImage imageNamed:dataObject];
    colorez = NO;
}

// draw functionality: 
- (IBAction)selectColor:(UIButton *)sender {
    UIButton * PressedButton = (UIButton*)sender;
    
    switch(PressedButton.tag)
    {
        case 0:
            red = 0.0/255.0;
            green = 0.0/255.0;
            blue = 0.0/255.0;
            break;
        case 1:
            red = 105.0/255.0;
            green = 105.0/255.0;
            blue = 105.0/255.0;
            break;
        case 2:
            red = 255.0/255.0;
            green = 0.0/255.0;
            blue = 0.0/255.0;
            break;
        case 3:
            red = 0.0/255.0;
            green = 0.0/255.0;
            blue = 255.0/255.0;
            break;
        case 4:
            red = 102.0/255.0;
            green = 204.0/255.0;
            blue = 0.0/255.0;
            break;
        case 5:
            red = 102.0/255.0;
            green = 255.0/255.0;
            blue = 0.0/255.0;
            break;
        case 6:
            red = 51.0/255.0;
            green = 204.0/255.0;
            blue = 255.0/255.0;
            break;
        case 7:
            red = 160.0/255.0;
            green = 82.0/255.0;
            blue = 45.0/255.0;
            break;
        case 8:
            red = 255.0/255.0;
            green = 102.0/255.0;
            blue = 0.0/255.0;
            break;
        case 9:
            red = 255.0/255.0;
            green = 255.0/255.0;
            blue = 0.0/255.0;
            break;
    }
}

- (IBAction)selectEraser:(id)sender {
    red = 255.0/255.0;
    green = 255.0/255.0;
    blue = 255.0/255.0;
    opacity = 1.0;
}

- (IBAction)goToMenu:(id)sender {
//    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (colorez) {
        mouseSwiped = NO;
        UITouch *touch = [touches anyObject];
        lastPoint = [touch locationInView:self.mainImg];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (colorez) {
        mouseSwiped = YES;
        UITouch *touch = [touches anyObject];
        CGPoint currentPoint = [touch locationInView:self.mainImg];
        
        UIGraphicsBeginImageContext(self.mainImg.frame.size);
        [self.activeDrawImg.image drawInRect:CGRectMake(0, 0, self.mainImg.frame.size.width, self.mainImg.frame.size.height)];
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
        CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);
        
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        self.activeDrawImg.image = UIGraphicsGetImageFromCurrentImageContext();
        [self.activeDrawImg setAlpha:opacity];
        UIGraphicsEndImageContext();
        
        lastPoint = currentPoint;
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
    if (colorez) {
        if(!mouseSwiped) {
            UIGraphicsBeginImageContext(self.mainImg.frame.size);
            [self.activeDrawImg.image drawInRect:CGRectMake(0, 0, self.mainImg.frame.size.width, self.mainImg.frame.size.height)];
            CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
            CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush);
            CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, opacity);
            CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
            CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
            CGContextStrokePath(UIGraphicsGetCurrentContext());
            CGContextFlush(UIGraphicsGetCurrentContext());
            self.activeDrawImg.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        
        UIGraphicsBeginImageContext(self.mainImg.frame.size);
        [self.mainImg.image drawInRect:CGRectMake(0, 0, self.mainImg.frame.size.width, self.mainImg.frame.size.height) blendMode:kCGBlendModeNormal alpha:1.0];
        [self.activeDrawImg.image drawInRect:CGRectMake(0, 0, self.mainImg.frame.size.width, self.mainImg.frame.size.height) blendMode:kCGBlendModeNormal alpha:opacity];
        self.mainImg.image = UIGraphicsGetImageFromCurrentImageContext();
        self.activeDrawImg.image = nil;
        UIGraphicsEndImageContext();
    }
}



- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    SettingsViewController * settingsVC = (SettingsViewController *)segue.destinationViewController;
    settingsVC.delegate = self;
    settingsVC.brush = brush;
    settingsVC.opacity = opacity;
    settingsVC.red = red;
    settingsVC.green = green;
    settingsVC.blue = blue;
    
    myPopover = [(UIStoryboardPopoverSegue *)segue popoverController];
}


#pragma mark - SettingsViewControllerDelegate methods

- (void)closeSettings:(UIButton *)sender tag:(int)tag{
    
    if (tag) {
        brush = ((SettingsViewController*)sender).brush;
        opacity = ((SettingsViewController*)sender).opacity;
        red = ((SettingsViewController*)sender).red;
        green = ((SettingsViewController*)sender).green;
        blue = ((SettingsViewController*)sender).blue;
    }
    
    [myPopover dismissPopoverAnimated:YES];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    // Was there an error?
    if (error != NULL)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Image could not be saved.Please try again"  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Close", nil];
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Image was successfully saved in photoalbum"  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Close", nil];
        [alert show];
    }
}
@end
